package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.mapper.InspectProjectDetailMapper;
import com.foreverwin.mes.lims.model.InspecArray;
import com.foreverwin.mes.lims.model.InspectProjectDetail;
import com.foreverwin.mes.lims.model.InspectTask;
import com.foreverwin.mes.lims.service.InspectTaskService;
import com.foreverwin.mes.lims.util.DataValueConstant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.InspectProjectService;
import com.foreverwin.mes.lims.model.InspectProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Levy
 * @since 2020-02-19
 */
@Controller
@RequestMapping("/inspectProjects")
public class InspectProjectController {
    private final Logger logger = LoggerFactory.getLogger(InspectProjectController.class);

    @Autowired
    public InspectProjectService inspectProjectService;

    @Autowired
    public InspectProjectDetailMapper inspectProjectDetailMapper;

    @Autowired
    public InspectTaskService inspectTaskService;

    /**
     * 保存检验项目
     *
     * @param jsonObject
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doSave", method = RequestMethod.POST)
    public AjaxResult stationCertificationSave(@RequestBody JSONObject jsonObject) {

        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();

        try {

            //参数
            String projectNo = null;
            String projectDesc = null;
            String checkType = null;
            String revision = null;
            String currentRevision = null;
            String dataGroup = null;

            Map<String, Object> map = (Map<String, Object>) jsonObject.get("project");
            if (map == null) {
                throw BusinessException.build("参数传递错误");
            }
            if (!map.containsKey("item") || StringUtils.isBlank(map.get("item") + "")) {
                throw BusinessException.build("检验项目编号不能为空");
            }
            if (!map.containsKey("itemDesc") || StringUtils.isBlank(map.get("itemDesc") + "")) {
                throw BusinessException.build("检验项目描述不能为空");
            }
            if (!map.containsKey("checkType") || StringUtils.isBlank(map.get("checkType") + "")) {
                throw BusinessException.build("检验项目编号不能为空");
            }
            if (!map.containsKey("reversion") || StringUtils.isBlank(map.get("reversion") + "")) {
                throw BusinessException.build("检验项目描述不能为空");
            }
            if (!map.containsKey("dcGroup") || StringUtils.isBlank(map.get("dcGroup") + "")) {
                throw BusinessException.build("检验项目编号不能为空");
            }

            projectNo = (String) map.get("item");
            projectDesc = (String) map.get("itemDesc");
            revision = (String) map.get("reversion");
            currentRevision = (String) map.get("currentVersion");
            dataGroup = (String) map.get("dcGroup");
            checkType = (String) map.get("checkType");

            /**
             * 检验项目主表数据组装
             */
            InspectProject inspectProject = new InspectProject();
            inspectProject.setSite( site );
            inspectProject.setProjectNo( projectNo );
            inspectProject.setProjectDesc( projectDesc );
            inspectProject.setCheckType( checkType );
            inspectProject.setRevision( revision );
            inspectProject.setCurrentRevision( currentRevision );
            inspectProject.setDataGroup( dataGroup );
            inspectProject.setCreatedUser( user );

            List<Map> projectList = (List<Map>) jsonObject.get("projectList");

            if ( projectList.isEmpty() ){
                throw BusinessException.build("缺少检验项目明细!");
            }

            inspectProjectService.doSave( inspectProject , projectList );

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }

        return AjaxResult.success("检验项目维护成功！");
    }

    /**
     * 查询检验项目
     *
     * @param inspectProject
     * @return
     */
    @ResponseBody
    @GetMapping("/getInspectProject")
    public AjaxResult getStationAndCertification(InspectProject inspectProject) {
        Map<String, Object> result = new HashMap<String, Object>();
        String site = CommonMethods.getSite();
        try {
            String projectBo = HandleEnum.INSPECT_PROJECT.getHandle( site , inspectProject.getProjectNo() ,inspectProject.getCheckType() , inspectProject.getRevision() );
            inspectProject =  inspectProjectService.selectById( projectBo );
            if ( inspectProject == null ){
                throw BusinessException.build("未找到对应数据");
            }
            Map paramMap = new HashMap();
            paramMap.put("PROJECT_BO",projectBo);
            List<InspectProjectDetail> inspectProjectDetails = inspectProjectDetailMapper.selectByMap( paramMap );
            List<Map> details = new ArrayList<>();
            if ( !inspectProjectDetails.isEmpty() ){
                for ( InspectProjectDetail inspectProjectDetail : inspectProjectDetails ){
                    Map detail = new HashMap();
                    detail.put("item",inspectProjectDetail.getItem());
                    detail.put("itemDesc",inspectProjectDetail.getItemDesc());
                    detail.put("dataType",inspectProjectDetail.getDataType());
                    detail.put("checkStandard",inspectProjectDetail.getCheckStandard());
                    if ( inspectProjectDetail.getStandardValue() != null ){
                        detail.put("standardValue",inspectProjectDetail.getStandardValue().stripTrailingZeros().toPlainString());
                    }
                    if ( inspectProjectDetail.getLowerLimit() != null ){
                        detail.put("lowerLimit",inspectProjectDetail.getLowerLimit().stripTrailingZeros().toPlainString());
                    }
                    if ( inspectProjectDetail.getUpperLimit() != null ){
                        detail.put("upperLimit",inspectProjectDetail.getUpperLimit().stripTrailingZeros().toPlainString());
                    }
                    if ( inspectProjectDetail.getSampleQty() != null ){
                        detail.put("sampleQty",inspectProjectDetail.getSampleQty().stripTrailingZeros().toPlainString());
                    }
                    if ( inspectProjectDetail.getSourceData() != null ){
                        detail.put("sourceData",inspectProjectDetail.getSourceData().stripTrailingZeros().toPlainString());
                    }

                    detail.put("arrayName",inspectProjectDetail.getArrayName());
                    detail.put("report",inspectProjectDetail.getReport());

                    details.add( detail );
                }
            }

            result.put("inspectProject", inspectProject);
            result.put("projectList", details);

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有检验项目数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getArrayList() {

        List<InspectProject> result = new ArrayList<InspectProject>();
        try {

            String site = CommonMethods.getSite();
            Map param = new HashMap();
            param.put("SITE" , site );
            param.put("STATUS" , "Y" );
            result = inspectProjectService.selectByMap( param );

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 删除
     * @param inspectProject
     * @return  null 失败
     */
    @ResponseBody
    @PostMapping(  "/doDelete")
    public AjaxResult inspecProjectDelete( @RequestBody InspectProject inspectProject ) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        boolean count=true;
        try {
            String projectNo = inspectProject.getProjectNo();
            String revision = inspectProject.getRevision();
            String checkType = inspectProject.getCheckType();
            String Handle = HandleEnum.INSPECT_PROJECT.getHandle( site , projectNo ,checkType , revision );
            InspectProject model = inspectProjectService.selectById( Handle );
            if ( model == null ){
                throw BusinessException.build("检验项目【"+ projectNo +"】不存在版本为【"+revision+"】的数据!");
            }

            Map paramMap = new HashMap();
            paramMap.put( "OBJECT" ,Handle );
            List<InspectTask> inspectTasks = inspectTaskService.selectByMap( paramMap );
            if ( inspectTasks.isEmpty() ){
                //检验任务状态
                inspectTasks.forEach( inspectTask -> {
                    String type = inspectTask.getTaskStatus();
                    String taskNo = inspectTask.getTaskId();
                    if ( !DataValueConstant.TASK_STATUS_DELETE.equals( type ) ){
                        throw BusinessException.build("检验项目【"+ projectNo +"】在任务【"+ taskNo +"】中使用，不可删除");
                    }
                } );
            }

            model.setStatus("D");
            count =  inspectProjectService.updateById( model );


        } catch (Exception e) {
            logger.error("inspecProjectDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == true ? "删除成功!" : "删除失败!");
    }
}